package cn.springcloud.fix.common.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class ConvertUtil extends ConvertUtils {

    public static Object convert(final String value, final Class<?> clazz) {
        Object result = null;

        if (clazz.equals(Date.class)) {
            SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                result = dateTimeFormat.parse(value);
            } catch (ParseException e) {
                log.error(e.getMessage(), e);
            }
            if (result == null) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    result = dateFormat.parse(value);
                } catch (ParseException e) {
                    throw new IllegalArgumentException("The value " + value + " can't convert to Date");
                }
            }
            return result;
        }

        return ConvertUtils.convert(value, clazz);
    }
}
